package com.kun.rental.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kun.rental.entity.User;
import com.kun.rental.service.IRoleService;
import com.kun.rental.service.IUserService;
import com.kun.rental.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ikun
 * @since 2024-07-04
 */
@RestController
@RequestMapping("/rental/user")
@Slf4j
@Tag(name = "用户管理")
public class UserController {

    @Autowired
    private IUserService userService;

    // 密码加密
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private IRoleService roleService;


    /**
     * 获取用户列表
     * @return
     */
    @Operation(summary = "获取用户列表")
    @GetMapping("/list")
    public Result<List<User>> list() {
        // 调用userService的list方法获取用户列表，并将结果封装在一个成功的Result对象中返回。
        return Result.success(userService.list());
    }


    /**
     * 分页查询用户信息
     * @param start
     * @param size
     * @param user
     * @return
     */
    @PostMapping("/{start}/{size}")
    public Result search(@PathVariable Integer start,
                         @PathVariable Integer size,
                         @RequestBody User user){
        Page<User> page = new Page<>(start, size);
        return Result.success(userService.searchByPage(page, user));
    }


    /**
     * 新增用户
     * @param user
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody User user){
        User user1 = userService.selectByUsername(user.getUsername());
        if (user1 != null){
            return Result.fail().setMessage("用户已存在");
        }else {
            //密码加密
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            user.setIsAdmin(0); // 新增的用户都为普通用户
            if (StrUtil.isEmpty(user.getAvatar())){
                // 设置默认头像
                user.setAvatar("https://q2.itc.cn/q_70/images03/20240320/3df8c75302424a05864e62215a548e28.jpeg");
            }
            return userService.save(user)?Result.success() : Result.fail();
        }
    }


    /**
     * 修改用户
     * @param user
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody User user){
        User user1 = userService.selectByUsername(user.getUsername());
        if (user1 != null && !Objects.equals(user1.getId(), user.getId())){
            return Result.fail().setMessage("用户已存在");
        }
        if (StrUtil.isEmpty(user.getAvatar())){
            // 设置默认头像
            user.setAvatar("https://q2.itc.cn/q_70/images03/20240320/3df8c75302424a05864e62215a548e28.jpeg");
        }
        return userService.updateById(user)?Result.success() : Result.fail();
    }


    /**
     * 删除用户
     * @param ids
     * @return
     */
    @DeleteMapping("/delete/{ids}")
    public Result delete(@PathVariable String ids){
        return userService.delete(ids) ? Result.success() : Result.fail();
    }

    // 根据用户id查询角色id
    @GetMapping("role/{userId}")
    public Result selectRoleByUserId(@PathVariable Integer userId){
        return Result.success(roleService.selectRoleIdByUserId(userId));
    }


    @GetMapping("bind/{userId}/{roleIds}")
    public Result bindRole(@PathVariable Integer userId,
                           @PathVariable String roleIds){
        List<Integer> list = Arrays.stream(roleIds.split(","))
                .map(Integer::parseInt)
                .toList();
        return userService.bindRole(userId,list)?Result.success():Result.fail();

    }




}
